package cn.pkubangbang.demo.democontact.service.impl;

import cn.pkubangbang.demo.democontact.entity.Person;
import cn.pkubangbang.demo.democontact.mapper.PersonMapper;
import cn.pkubangbang.demo.democontact.service.PersonService;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: zhangzhenbang@k2data.com.cn
 * @Date: 2018-08-23 17:48
 */
@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonMapper personMapper;

    @Override
    public Person getPersonById(Integer id) {
        return personMapper.getPersonById(id);
    }

    @Override
    public List<Person> findPersonByName(String name) {
        return personMapper.findPersonByName(name);
    }

    @Override
    public List<Person> queryFriends(Person p) {
        return personMapper.queryFriends(p);
    }

    @Override
    public List<Person> peopleMayKnow(Person p) {
        return personMapper.peopleMayKnow(p);
    }

    @Override
    public boolean acquaintant(List<Person> people1) {

        // convert to array to speed up the data access.
        Person[] people = people1.toArray(new Person[0]);

        for (int i = 0; i < people.length - 1; i++) {
            Set<Person> friends = new HashSet<>(personMapper.queryFriends(people[i]));
            // note 算法！不要把自己算进来！
            for (int j = i + 1; j < people.length; j++) {
                Person p = people[j];
                if (!friends.contains(p)) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public boolean acquaintant(Person p1, Person p2) {
        return personMapper.getContactByTwoPeople(p1, p2).getId() != null;
    }
}
